<template>
  <my-dialog title="Task" :ok="assign" :mode="props.style ? props.style : ''">
    <q-card-section>
      <div class="q-pa-sm" v-if="p_stock_code">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">Stock Code:</q-item-label>
          <q-select
            v-model="stock_code"
            dense
            class="input-css col-8 fal"
            borderless
            use-input
            :options="stockOpts"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> No results </q-item-section>
              </q-item>
            </template></q-select
          >
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal"
            >M' tce Type:<span style="color: red">*</span></q-item-label
          >
          <q-select
            borderless
            v-model="mtce_type"
            input-debounce="0"
            hide-bottom-space
            lazy-rules
            :options="['CM', 'PM', 'NM', 'IGI']"
            class="col-8 fal input-css"
            :dense="true"
          >
          </q-select>
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">Task:<span style="color: red">*</span></q-item-label>
          <q-select
            v-model="task"
            dense
            class="col-8 fal input-css"
            borderless
            use-input
            :options="taskOpts"
            @filter="filterTaskFn"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> No results </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">E-Form:</q-item-label>

          <q-select
            v-model="eform"
            dense
            class="col-8 fal input-css"
            borderless
            use-input
            hide-bottom-space
            :options="eformOpts"
            @filter="filterEformFn"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> No results </q-item-section>
              </q-item>
            </template>
            </q-select
          >
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">Type:</q-item-label>
          <q-checkbox v-model="cur_tab" label="Current Task" color="primary" />
          <q-checkbox v-model="final_tab" label="Final Check" color="primary" />
        </div>
      </div>
    </q-card-section>
  </my-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { EformSchemas } from 'src/services/type';
import { useQuasar } from 'quasar';
import { getTaskByType, getTasks } from 'src/services/tasksService';
import {
  assignTask,
  updateCurStockItemTask,
} from 'src/services/stockItemtasksService';
import {
  getEformSchema,
  getEformSchemas,
} from 'src/services/eformSchemasService';
import { getChildStockItems } from 'src/services/stockCodeService';
import MyDialog from '../container/MyDialog.vue';

const task = ref('');
const cur_tab = ref(false);
const final_tab = ref(false);
const mtce_type = ref('');

const toptions = ref<string[]>([]);
const taskOpts = ref<string[]>([]);

const taskMap = new Map();

const eform = ref('');
const eoptions = ref<string[]>([]);
const eformOpts = ref<string[]>([]);

const eforms: EformSchemas[] = [];
const stock_code = ref('');

const stockOpts = ref<string[]>([]);

const emit = defineEmits(['update', 'close']);

const $q = useQuasar();

const props = defineProps<{
  style: 'edit' | 'assign';
  stock_id: number;
  taskItem?: {
    id: number;
    stock_item: {
      id: number;
      stock_code: string;
    };
    name: string;
    eform_schema_id: number;
    has_eform: boolean;
    mtce_type: string;
    cur_tab: boolean;
    final_tab: boolean;
  };
  p_stock_code?: string;
}>();



async function getTasksData() {
/*   const res = await getTasks();
  if (res.data) {
    const data: string[] = [];
    for (let r of res.data) {
      data.push(r.task);
      taskMap.set(r.mtce_type, r);
    }
    taskOpts.value = [...data];
    toptions.value = [...data];
  } */
  const res = await getTaskByType(mtce_type.value)
    if (res.data) {
    const data: string[] = [];
    for (let r of res.data.data) {
      data.push(r.task);
      taskMap.set(r.task, r);
    }
    taskOpts.value = [...data];
    toptions.value = [...data];
  }
}

async function getDisplayTab() {
  const taskobj = taskMap.get(task.value);
  if (taskobj) {

    cur_tab.value = taskobj.cur_tab;
    final_tab.value = taskobj.final_tab;
    const e = eformOpts.value.filter((o)=>{
      return o.includes(taskobj.wi_no)
    }) 
    eform.value = e[0]
  }
}


async function getEformData() {
  const res = await getEformSchemas();
  if (res.data) {
    console.log(res.data);
    
    const title = [];
    for (let data of res.data) {
      eforms.push(data);
      title.push(data.formNo + ' - ' +data.title);
    }
    eformOpts.value = [...title];
    eoptions.value = [...title];
  }
}
const stockItemTask: {
  stock_item: number;
  name: string;
  eform_schema_id?: number;
  mtce_type: string;
  cur_tab: boolean;
  final_tab: boolean;
  formNo?: string
} = {
  stock_item: 0,
  name: '',
  mtce_type: '',
  cur_tab: false,
  final_tab: false,
};

async function assign() {
  stockItemTask.stock_item = props.stock_id;
  stockItemTask.name = task.value;
  stockItemTask.mtce_type = mtce_type.value;
  stockItemTask.cur_tab = cur_tab.value;
  stockItemTask.final_tab = final_tab.value;
  const eform_schema = eforms.find((o) =>{ 
    return `${o.formNo} - ${o.title}` === eform.value
  });
  if (props.style == 'assign') {
    stockItemTask.eform_schema_id = eform_schema?.id;
    stockItemTask.formNo = eform_schema?.formNo
    const res = await assignTask(stockItemTask);

    if (res.data) {
      $q.notify({
        color: 'positive',
        position: 'bottom',
        message: 'Success',
      });
    }
  }
  if (props.style == 'edit') {
    stockItemTask.eform_schema_id = eform_schema?.id;
    stockItemTask.formNo = eform_schema?.formNo
    if (props.taskItem) {
      const res = await updateCurStockItemTask(
        props.taskItem?.id,
        stockItemTask
      );

      if (res.data) {
        $q.notify({
          color: 'positive',
          position: 'bottom',
          message: 'Success',
        });
      }
    }
  }
  emit('update');
  emit('close');
}

function filterTaskFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      taskOpts.value = [...toptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    taskOpts.value = toptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

function filterEformFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      eformOpts.value = [...eoptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    eformOpts.value = eoptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

async function getChildStockCode() {
  if (props.p_stock_code) {
    stockOpts.value.push(props.p_stock_code);
    const res = await getChildStockItems(props.p_stock_code);
    if (res.data) {
      for (let d of res.data) {
        stockOpts.value.push(d.child.stock_code);
      }
    }
  }
}

async function init() {
  await getEformData();
  await getTasksData();
  await getChildStockCode();
}

onMounted(() => {
  if (props.taskItem) {
    if (props.taskItem.has_eform) {
      getEformSchema(props.taskItem.eform_schema_id).then((res) => {
        const title = res.data.title;
        eform.value = title;
      });
    }
    task.value = props.taskItem.name;
    mtce_type.value = props.taskItem.mtce_type;
    final_tab.value = props.taskItem.final_tab;
    cur_tab.value = props.taskItem.cur_tab;
  }
  init();
});

watch(mtce_type, () => {
  getTasksData();
});

watch(task, () => {
  getDisplayTab();
});
</script>
